#include <gtest/gtest.h>
#include "filter.h"

extern "C" {
    #include "filter.h"
}

// 测试滤波器创建和销毁
TEST(MovingAverageFilterTest, CreateAndDestroy) {
    MovingAverageFilter* filter = moving_average_filter_create(5);
    EXPECT_NE(filter, nullptr);
    EXPECT_EQ(filter->size, 5);
    EXPECT_EQ(filter->count, 0);
    
    moving_average_filter_destroy(filter);
}

// 测试空滤波器创建
TEST(MovingAverageFilterTest, CreateWithInvalidSize) {
    MovingAverageFilter* filter = moving_average_filter_create(0);
    EXPECT_EQ(filter, nullptr);
    
    filter = moving_average_filter_create(-1);
    EXPECT_EQ(filter, nullptr);
}

// 测试滤波器更新和输出
TEST(MovingAverageFilterTest, UpdateAndOutput) {
    MovingAverageFilter* filter = moving_average_filter_create(3);
    ASSERT_NE(filter, nullptr);
    
    // 第一次更新
    float result = moving_average_filter_update(filter, 1.0f);
    EXPECT_FLOAT_EQ(result, 1.0f);
    EXPECT_EQ(filter->count, 1);
    
    // 第二次更新
    result = moving_average_filter_update(filter, 2.0f);
    EXPECT_FLOAT_EQ(result, 1.5f);
    EXPECT_EQ(filter->count, 2);
    
    // 第三次更新
    result = moving_average_filter_update(filter, 3.0f);
    EXPECT_FLOAT_EQ(result, 2.0f);
    EXPECT_EQ(filter->count, 3);
    
    // 第四次更新（缓冲区已满）
    result = moving_average_filter_update(filter, 4.0f);
    EXPECT_FLOAT_EQ(result, 3.0f); // (2+3+4)/3 = 3.0
    EXPECT_EQ(filter->count, 3);
    
    moving_average_filter_destroy(filter);
}

// 测试滤波器重置
TEST(MovingAverageFilterTest, Reset) {
    MovingAverageFilter* filter = moving_average_filter_create(3);
    ASSERT_NE(filter, nullptr);
    
    moving_average_filter_update(filter, 1.0f);
    moving_average_filter_update(filter, 2.0f);
    
    EXPECT_EQ(filter->count, 2);
    EXPECT_FLOAT_EQ(filter->sum, 3.0f);
    
    moving_average_filter_reset(filter);
    
    EXPECT_EQ(filter->count, 0);
    EXPECT_FLOAT_EQ(filter->sum, 0.0f);
    
    moving_average_filter_destroy(filter);
}

// 测试边界情况
TEST(MovingAverageFilterTest, EdgeCases) {
    MovingAverageFilter* filter = moving_average_filter_create(1);
    ASSERT_NE(filter, nullptr);
    
    float result = moving_average_filter_update(filter, 5.0f);
    EXPECT_FLOAT_EQ(result, 5.0f);
    
    result = moving_average_filter_update(filter, 10.0f);
    EXPECT_FLOAT_EQ(result, 10.0f);
    
    moving_average_filter_destroy(filter);
}

// 测试空指针安全
TEST(MovingAverageFilterTest, NullPointerSafety) {
    moving_average_filter_update(nullptr, 1.0f);
    moving_average_filter_reset(nullptr);
    moving_average_filter_destroy(nullptr);
    
    float result = moving_average_filter_get_output(nullptr);
    EXPECT_FLOAT_EQ(result, 0.0f);
}